﻿using Microsoft.Extensions.Logging;
using NuGet.Protocol.Core.Types;
using NuGet.Versioning;
using QuickGet.Core.Services;

namespace QuickGet.Core
{
    public record ListPackageVersionsCommand(string PackageId, string PackageSourceName);

    public class ListPackageVersions : NugetOperationBase
    {
        public ListPackageVersions(
            ILogger<ListPackageVersions> logger, 
            SourceCacheContext sourceCache, 
            INugetResourceResolver nugetResourceResolver, 
            INugetSourceRepositoryResolver nugetSourceRepositoryResolver) 
            : base(
                  logger, 
                  sourceCache, 
                  nugetResourceResolver, 
                  nugetSourceRepositoryResolver)
        {
        }

        public async Task<List<NuGetVersion>> ExecuteAsync(ListPackageVersionsCommand command, CancellationToken cancellationToken)
        {
            var resource = await GetFindPackageByIdResourceAsync(command.PackageSourceName, cancellationToken);

            if(resource is null)
            {
                return [];
            }

            var versions = await resource.GetAllVersionsAsync(command.PackageId, _sourceCache, _nugetLogger, cancellationToken);

            return versions.ToList();
        }
    }
}
